﻿from numpy import *
import functools

def count_classes(cs):
    r = {}
    for c in cs:
        r[c] = r.get(c, 0) + 1
    return r

class NaiveBayes:
    def __init__(self):
        pass

    def train(self, xs, cs):
        (self.xs, self.cs) = (xs, cs)

        
        pass

    def classify(self, xs):
        pass


def textParse(string):
    import re
    listOfTokens = re.split(r'\W*', string)
    return [tok.lower() for tok in listOfTokens if len(tok) > 2]

def train0(props, labels):
    pass


def classify0(x):

    pass

def train(proportion, labels):
    """
    """
    labels_frequency = frequency(labels)
    
    conditionalFrequency = {}
    conditionalTotal = {}
    for i in range(len(category)):
        conditionalFrequency[category[i]] = conditionalFrequency.get(category[i], ones(len(proportion[0]))) + proportion[i]
        conditionalTotal[category[i]] = conditionalTotal.get(category[i], 2.0) + sum(proportion[i])

    for k in conditionalFrequency.keys():
        conditionalFrequency[k] = conditionalFrequency[k] / conditionalTotal[k]
        
    return conditionalFrequency, categoryFrequency

def classify(text, conditionalProbability, categoryProbability):
    probability = -inf
    category = None
    for k in categoryProbability.keys():
        p = sum(log(conditionalProbability[k])*text) + log(categoryProbability[k])
        if (p > probability):
            probability = p
            category = k
   
    return category, exp(probability)

def count_labels(labels):
    count = {}
    for l in labels:
        count[l] = count.get(l, 0) + 1
    return count

def frequency(labels):
    sz = len(labels)*1.0
    r = count_labels(labels)
    for k in r.keys():
        r[k] = r[k] / sz
    return r
    


def getWordsFromTexts(texts):
    return list(functools.reduce(lambda x,y : set(x) | set(y), texts)) 

def _countWordsInText(text, words):
    prop = zeros(len(words))
    for w in text:
        if w in words:
            prop[words.index(w)] += 1
    return prop


def countWordsInTexts(texts, words):
    prop = zeros((len(texts),len(words)))

    for i in range(len(texts)):
        prop[i] = _countWordsInText(texts[i], words)

    return prop
    

